﻿using BaseData.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseData.Infrastructure.Implements
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 上下文
        /// </summary>
        private readonly DataDbContext db;
        /// <summary>
        /// 数据库上下文
        /// </summary>
        public DataDbContext DB
        {
           get { return db; }
        }
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">上下文</param>
        public BaseRepository(DataDbContext db)
        {
            this.db = db;
            
        }

        // <summary>
        /// 获取全部
        /// </summary>
        /// <returns>返回集合</returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响行数</returns>
        public async Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
       public async Task<int> AddRange(IEnumerable<T> entities)
        {
            await db.Set<T>().AddRangeAsync(entities);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
       public async Task<int> UpdateRange(IEnumerable<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetById(int id)
        {
            return await db.Set<T>().FindAsync(id);
           
        }

        public async Task<int> DeleteAsync(T entity)
        {
           db.Set<T>().Remove(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteRange(IEnumerable<T> entities)
        {
            db.Set<T>().RemoveRange(entities);
            return await db.SaveChangesAsync();
        }
    }
}
